package com.apple1.commonutil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 将vo对象里面的有效的成员变量的值 映射到 数据库实体对象的成员变量
 *
 * @author cc
 */

public class BeanMapUtil {

    public static <T>  T  getMapBean(Object src,Class<T> des) {

        if (src == null){
            return null;
        }
        T desObj = null;
        try {
            desObj = des.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        Map<String,Object> map = new HashMap<>();

        Class clazz = src.getClass();

        Field[] srcFields = clazz.getDeclaredFields();
        Field[] desFields =  des.getDeclaredFields();

        for (Field srcField : srcFields){
            srcField.setAccessible(true);
          String srcFieldName = srcField.getName();
            Object valueObj = null;
            try {
                valueObj = srcField.get(src);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            //遍历目标对象的成员变量
          for(Field desfield:desFields){
              desfield.setAccessible(true);
              String desFieldName = desfield.getName();
              if(srcFieldName.equals(desFieldName)){
                  if(valueObj != null){
                      try {
                          desfield.set(desObj,valueObj);
                      } catch (IllegalAccessException e) {
                          e.printStackTrace();
                      }
                  }
                  break;
              }
          }

        }


        return desObj;
    }



}
